﻿(function ($) {
    //选择表单项的值       Chiron
    $.fn.getVals = function (selector, key) {
        var vals = new Array();
        $(selector, $(this)).each(function () {
            var $this = $(this);
            vals.push($this.val());
        });
        if (typeof (key) == "undefined" || !key) {
            return vals;
        } else {
            key = new String(key);
            if (key.indexOf("=") == -1) key += "=";
            var key2 = key;
            if (key2.indexOf("&") == -1) key2 = "&" + key2;
            return key + vals.join(key2);
        }
    }
    $(function () {
        //Ajax Form   Chiron
        $(".ajax-form .submit").live("click", function () {
            var $submitBtn = $(this);
            var $form = $submitBtn.parents(".ajax-form:first");
            if ($form.attr("action")) {
                var args = {};
                $form.find("[name]").each(function () {
                    var $arg = $(this);
                    args[$arg.attr("name")] = $arg.val();
                });

                if ($form.attr("ajax-begin")) {
                    Function($form.attr("ajax-begin"))();
                }
                $.post($form.attr("action"), args, function (result) {
                    if ($form.attr("ajax-complete")) {
                        Function($form.attr("ajax-complete"))();
                    }
                    if ($form.attr("ajax-update")) {
                        $($form.attr("ajax-update")).html(result);
                    }
                });
            }
        });
        //复制当前页地址   Chiron
        $(".copy-cur-url").live("click", function () {
            if (copyToClipBoard(window.location)) {
                alert("网址已复制到剪贴板.");
            }
        });
        //打印当前页面
        $(".print-page").live("click", function () {
            print();
        });
        //链接功能      Chiron
        $("[link]").live("click", function () {
            var $this = $(this);
            if ($this.attr("link")) {
                window.open($this.attr("link"), $this.attr("target"))
                return false;
            }
        }).each(function () {
            var $this = $(this);
            $this.css({ cursor: "pointer" });
        }).find("a").live("click", function () {
            $aTag = $(this);
            if ($aTag.attr("href")) {
                window.open($aTag.attr("href"), $aTag.attr("target"));
                return false;
            }
        });
        //自动加载功能    Chiron
        $(".auto-load[rel][ev][data-url]").each(function () {
            var $this = $(this);
            if (!($this.attr("justonce") == "true" && $this.attr("loaded") == "true")) {
                $($this.attr("rel")).live($this.attr("ev"), function () {
                    $.hu8.showLoading();
                    var args = {};
                    try {
                        args = eval("(" + $this.attr("args") + ")");
                    } catch (ex) { }
                    $.post($this.attr("data-url"), args, function (result) {
                        $.hu8.hideLoading();
                        $this.html(result);
                        $this.attr("loaded", "true");
                    });
                });
            }
            if ($this.attr("first-time-load") == "true") $($this.attr("rel"))[$this.attr("ev")]();
        });
        //滚动框   Chiron
        $(".scroll-box").each(function () {
            var $this = $(this);
            $this.css("overflow", "hidden");

            var itemsSel = $this.attr("scroll-items-sel") || ".items";
            var itemSel = $this.attr("scroll-item-sel") || ".item";
            var direction = $this.attr("scroll-direction") || "left";
            var interval = Number($this.attr("scroll-interval") || 5000);
            var speed = Number($this.attr("scroll-speed") || 500);
            var hoverStop = !($this.attr("scroll-hover-stop") == "false");

            var moveSize = direction == "up" || direction == "down" ?
                $this.find(itemSel + ":first").outerHeight(true) :
                $this.find(itemSel + ":first").outerWidth(true);

            var mStyleName = "margin-" + (direction == "up" || direction == "down" ? "top" : "left");

            var move = function (d) {
                var $items = $this.find(itemsSel);
                var props = {};
                if (d > 0) {
                    props[mStyleName] = -1 * moveSize;
                    $items.animate(props, speed, function () {
                        $items.css(mStyleName, 0);
                        $items.find(itemSel + ":first").appendTo($items);
                    });
                } else {
                    $items.css(mStyleName, -1 * moveSize);
                    $items.find(itemSel + ":last").prependTo($items);
                    props[mStyleName] = 0;
                    $items.animate(props, speed);
                }
            };
            var movePrev = function () {
                move(direction == "down" || direction == "right" ? 1 : -1);
            };
            var moveNext = function () {
                move(direction == "down" || direction == "right" ? -1 : 1);
            };

            var timeId;
            var runing = false;

            var start = function () {
                try {
                    clearTimeout(timeId);
                } catch (ex) { };

                if (runing) {
                    moveNext();
                } else {
                    runing = true;
                }
                timeId = setTimeout(start, interval);
            };

            var stop = function () {
                try {
                    clearTimeout(timeId);
                } catch (ex) { };
                runing = false;
            };

            if (hoverStop) {
                $this.hover(function () {
                    stop();
                }, function () {
                    start();
                });
            }

            start();
        });
        //选中全部      Chiron
        $(".selectAll[type=checkbox][rel]").live("click", function () {
            var $this = $(this);
            if ($this.is(":checked")) {
                $($this.attr("rel")).attr("checked", "checked");
            } else {
                $($this.attr("rel")).removeAttr("checked");
            }
        });
        //通用命令操作        Chiron
        $("#commands.commands #execute").live("click", function () {
            var $this = $(this);
            var $cmdBox = $this.parents("#commands:first");
            var $optype = $("[name=optype]:checked", $cmdBox);
            if ($optype.size() < 1) {
                box.alert("提示", "请选择一个操作!");
                return;
            }
            box.confirm("询问", "确定要执行选中的操作？", function () {
                $.hu8.showLoading();
                var url = $optype.val();
                var args = eval("(" + $optype.attr("args") + ")");
                $.post(url, args, function (result) {
                    $.hu8.hideLoading();
                    if (result.success) {
                        $.hu8.showLoading();
                        $.post($this.attr("data-url"), function (html) {
                            $.hu8.hideLoading();
                            $($this.attr("rel")).html(html);
                        });
                    } else {
                        box.error(result.message);
                    }
                });
            });
        });
    });
})(jQuery);
/**
* 作者：福州刘宝宝网络科技
* http://www.liubaobao.cn
* 2011年10月20日
**/
/****************************************String扩张程序**************************************/
String.prototype.endsWith = function (suffix) {
    return this.match(suffix + "$") == suffix;
};

String.prototype.startsWith = function (prefix) {
    return this.indexOf(prefix) === 0;
}

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.lTrim = function () {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.rTrim = function () {
    return this.replace(/(\s*$)/g, "");
}
//去掉最后一个字节
String.prototype.removeLastChar = function () {
    return this.substr(0, this.length - 1);
}

String.prototype.isNullOrEmpty = function () {
    if (this == null || this == undefined || this == "") {
        return true;
    } else {
        if (this.trim() == "") {
            return true;
        }
        return false;
    }
}
String.prototype.removeAfter = function (spliter) {
    return this.split(spliter)[0];
};

String.prototype.pxToInt = function () {
    try {
        var i = parseInt(this.substring(0, (this.length - 2)))
        if (isNaN(i)) {
            i = 0;
        }
        return i;
    } catch (err) {
        return 0;
    }
};

//生成 GUID
function Guid() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

/* object to string */
/** 需要更多的测试 **/
function objToString(o) {
    var r = [], i, j = 0, len;
    if (o == null) {
        return "\"\"";
    }
    if (typeof o == 'string') {
        return '"' + o + '"';
    }
    if (typeof o == 'object') {
        if (!o.sort) {
            r[j++] = '{';
            for (i in o) {
                //r[j++] = '"';
                r[j++] = i;
                r[j++] = ":";
                //  r[j++] = '":';
                r[j++] = objToString(o[i]);
                r[j++] = ',';
            }
            //可能的空对象
            //r[r[j-1] == '{' ? j:j-1]='}';
            r[j > 1 ? j - 1 : j] = '}';
        } else {
            r[j++] = '[';
            for (i = 0, len = o.length; i < len; ++i) {
                r[j++] = objToString(o[i]);
                r[j++] = ',';
            }
            //可能的空数组
            r[len == 0 ? j : j - 1] = ']';
        }
        return r.join('');
    }
    return o.toString();
}

var rgbToHex = function (rgbString) {
    if (rgbString != undefined && rgbString != null) {
        var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        if (parts != null) {
            delete (parts[0]);
            for (var i = 1; i <= 3; ++i) {
                parts[i] = parseInt(parts[i]).toString(16);
                if (parts[i].length == 1) parts[i] = '0' + parts[i];
            }
            var hexString = parts.join('');
            return "#" + hexString;
        }
    }
    return rgbString;
}



//继承
Function.prototype.extend = function (parentClass) {
    if (parentClass.constructor == Function) {
        this.prototype = new parentClass;
        this.prototype.contructor = this;
        this.prototype.parent = parentClass.prototype;
    } else {
        this.prototype = parentClass;
        this.prototype.constructor = this;
        this.prototype.parent = parentClass;
    }
    return this;
}

//为SOSO5的WebService使用的post
jQuery.iPost = function (url, data, postAction, errorAction) {
    var attrs = null;
    if (data) {
        attrs = objToString(data);
    }
    $.ajax({
        url: url,
        type: "POST",
        data: attrs,
        async: true,
        contentType: 'application/json; charset=utf-8',
        success: postAction,
        error: errorAction,
        complete: function () {

        }
    });
}
try {
    window.alert = showDialog;
} catch (ex) { }
//取得参数值
function getQArg(name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(location.href)) return unescape(RegExp.$2.replace(/\+/g, " ")); return "";
};

//复制到剪贴板,成功返回 true.    Chiron
var copyToClipBoard = function (data) {
    try {
        if (window.clipboardData) {
            window.clipboardData.setData("Text", data);
            return true;
        } else if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
                alert("被浏览器拒绝！\n请在浏览器地址栏输入[about:config]并回车\n然后将[signed.applets.codebase_principal_support]属性设置为[true]");
                return false;
            }
            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) {
                return false;
            }
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans) {
                return false;
            }
            trans.addDataFlavor('text/unicode');
            var str = new Object();
            var len = new Object();
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            var copytext = data;
            str.data = copytext;
            trans.setTransferData("text/unicode", str, copytext.length * 2);
            var clipid = Components.interfaces.nsIClipboard;
            if (!clipid) {
                return false;
            }
            clip.setData(trans, null, clipid.kGlobalClipboard);
        }
        return true;
    } catch (ex) {
        return false;
    }
}
